import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, Image, Popconfirm, message, Modal, Dropdown, Switch } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, MoreOutlined, EyeOutlined, CopyOutlined } from '@ant-design/icons';
import { getBannerList, deleteBanner, updateBannerStatus, copyBanner } from '@/services/contentManagementApi';
import BannerForm from './components/BannerForm';
import BannerPreview from './components/BannerPreview';

const BannerList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [bannerFormVisible, setBannerFormVisible] = useState(false);
  const [bannerPreviewVisible, setBannerPreviewVisible] = useState(false);
  const [currentBanner, setCurrentBanner] = useState<CONTENT.BannerModel | undefined>();
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');

  // 状态标签颜色映射
  const statusColorMap = {
    active: 'green',
    inactive: 'orange',
    expired: 'red',
  };

  // 位置标签颜色映射
  const positionColorMap = {
    home_top: 'blue',
    home_middle: 'cyan',
    course_top: 'purple',
    activity_top: 'orange',
  };

  // 表格列定义
  const columns: ProColumns<CONTENT.BannerModel>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      search: false,
    },
    {
      title: '轮播图',
      dataIndex: 'image',
      width: 120,
      search: false,
      render: (_, record) => (
        <Image
          src={record.image}
          alt={record.title}
          width={80}
          height={45}
          style={{ objectFit: 'cover', borderRadius: 4 }}
          fallback=""
        />
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 200,
      ellipsis: true,
      copyable: true,
    },
    {
      title: '位置',
      dataIndex: 'position',
      width: 120,
      valueType: 'select',
      valueEnum: {
        home_top: { text: '首页顶部', status: 'Processing' },
        home_middle: { text: '首页中部', status: 'Success' },
        course_top: { text: '课程页顶部', status: 'Warning' },
        activity_top: { text: '活动页顶部', status: 'Error' },
      },
      render: (_, record) => {
        const positionMap = {
          home_top: '首页顶部',
          home_middle: '首页中部',
          course_top: '课程页顶部',
          activity_top: '活动页顶部',
        };
        return (
          <Tag color={positionColorMap[record.position]}>
            {positionMap[record.position]}
          </Tag>
        );
      },
    },
    {
      title: '排序',
      dataIndex: 'sort_order',
      width: 80,
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      valueType: 'select',
      valueEnum: {
        active: { text: '启用', status: 'Success' },
        inactive: { text: '禁用', status: 'Warning' },
        expired: { text: '已过期', status: 'Error' },
      },
      render: (_, record) => (
        <Tag color={statusColorMap[record.status]}>
          {record.status === 'active' ? '启用' : record.status === 'inactive' ? '禁用' : '已过期'}
        </Tag>
      ),
    },
    {
      title: '点击次数',
      dataIndex: 'click_count',
      width: 100,
      search: false,
      render: (count) => count?.toLocaleString() || 0,
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      width: 160,
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '结束时间',
      dataIndex: 'end_time',
      width: 160,
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="preview"
          type="link"
          size="small"
          onClick={() => handlePreview(record)}
        >
          预览
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'edit',
                label: '编辑',
                icon: <EditOutlined />,
                onClick: () => handleEdit(record),
              },
              {
                key: 'copy',
                label: '复制',
                icon: <CopyOutlined />,
                onClick: () => handleCopy(record),
              },
              {
                key: 'status',
                label: record.status === 'active' ? '禁用' : '启用',
                onClick: () => handleStatusChange(record),
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 处理预览
  const handlePreview = (record: CONTENT.BannerModel) => {
    setCurrentBanner(record);
    setBannerPreviewVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: CONTENT.BannerModel) => {
    setCurrentBanner(record);
    setEditMode('edit');
    setBannerFormVisible(true);
  };

  // 处理复制
  const handleCopy = async (record: CONTENT.BannerModel) => {
    try {
      await copyBanner(record.id, `${record.title} - 副本`);
      message.success('轮播图复制成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('轮播图复制失败');
    }
  };

  // 处理状态变更
  const handleStatusChange = (record: CONTENT.BannerModel) => {
    const newStatus = record.status === 'active' ? 'inactive' : 'active';
    const actionText = newStatus === 'active' ? '启用' : '禁用';
    
    Modal.confirm({
      title: `确认${actionText}`,
      content: `确定要${actionText}轮播图 "${record.title}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await updateBannerStatus(record.id, newStatus);
          message.success(`轮播图${actionText}成功`);
          actionRef.current?.reload();
        } catch (error) {
          message.error(`轮播图${actionText}失败`);
        }
      },
    });
  };

  // 处理删除
  const handleDelete = (record: CONTENT.BannerModel) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除轮播图 "${record.title}" 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteBanner(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理新建
  const handleCreate = () => {
    setCurrentBanner(undefined);
    setEditMode('create');
    setBannerFormVisible(true);
  };

  // 处理批量状态更新
  const handleBatchStatusUpdate = async (status: 'active' | 'inactive') => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要操作的轮播图');
      return;
    }

    const actionText = status === 'active' ? '启用' : '禁用';
    
    Modal.confirm({
      title: `批量${actionText}`,
      content: `确定要${actionText}选中的 ${selectedRowKeys.length} 个轮播图吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          await Promise.all(
            selectedRowKeys.map(id => updateBannerStatus(id, status))
          );
          message.success(`批量${actionText}成功`);
          setSelectedRowKeys([]);
          actionRef.current?.reload();
        } catch (error) {
          message.error(`批量${actionText}失败`);
        }
      },
    });
  };

  return (
    <PageContainer>
      <ProTable<CONTENT.BannerModel>
        headerTitle="轮播图列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建轮播图
          </Button>,
        ]}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        tableAlertOptionRender={() => (
          <Space size={16}>
            <a onClick={() => handleBatchStatusUpdate('active')}>批量启用</a>
            <a onClick={() => handleBatchStatusUpdate('inactive')}>批量禁用</a>
          </Space>
        )}
        request={async (params, sort) => {
          const response = await getBannerList({
            page: params.current,
            limit: params.pageSize,
            title: params.title,
            position: params.position,
            status: params.status,
          });
          return {
            data: response.data.list,
            success: response.code === 200,
            total: response.data.pagination.total,
          };
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        scroll={{ x: 1400 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 轮播图表单弹窗 */}
      <BannerForm
        visible={bannerFormVisible}
        mode={editMode}
        initialValues={currentBanner}
        onCancel={() => setBannerFormVisible(false)}
        onSuccess={() => {
          setBannerFormVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 轮播图预览弹窗 */}
      <BannerPreview
        visible={bannerPreviewVisible}
        banner={currentBanner}
        onCancel={() => setBannerPreviewVisible(false)}
      />
    </PageContainer>
  );
};

export default BannerList;
